package openai

import (
	"encoding/json"
	"fmt"

	"github.com/EDDYCJY/go-gin-example/models"
	"github.com/EDDYCJY/go-gin-example/pkg/app"
	"github.com/EDDYCJY/go-gin-example/routers/internal"
	"github.com/EDDYCJY/go-gin-example/services"

	"github.com/EDDYCJY/go-gin-example/pkg/openai/aijieyun/pkg/services/aecs"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/ecs"
	"github.com/gin-gonic/gin"
	log "github.com/sirupsen/logrus"
)

type CreateInstanceRequest struct {
	*ecs.CreateInstanceRequest
	LeaseTimeSecond int //unit second
}

type CreateInstanceWork struct {
	*aecs.Client
	*ecs.CreateInstanceRequest
	*ecs.CreateInstanceResponse
}

func NewCreateInstanceWork(client *aecs.Client, req *ecs.CreateInstanceRequest) *CreateInstanceWork {
	return &CreateInstanceWork{
		Client:                client,
		CreateInstanceRequest: req,
	}
}

func (w *CreateInstanceWork) DoWork() error {
	response, err := w.Client.CreateInstance(w.CreateInstanceRequest)
	if err != nil {
		return err
	}
	w.CreateInstanceResponse = response
	return nil
}

func (w *CreateInstanceWork) GetID() string {
	if w.CreateInstanceResponse != nil {
		return w.CreateInstanceResponse.InstanceId
	}
	return ""
}

func CreateInstance(c *gin.Context) {
	appG := app.Gin{C: c}
	ecsRequst := ecs.CreateCreateInstanceRequest()
	createInstanceRequest := &CreateInstanceRequest{CreateInstanceRequest: ecsRequst}
	err := c.BindQuery(createInstanceRequest)
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}

	mash, err := json.Marshal(createInstanceRequest)
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}

	log.Debugf("--------input:\n%+v\n--------\n", string(mash))

	client := aecs.DefaultClient
	request := createInstanceRequest.CreateInstanceRequest
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}

	db := models.GetDB()
	work := NewCreateInstanceWork(&client, request)

	orderProcess := services.NewOrderProcess(db, work)

	var userID = uint64(c.GetInt64("user_id"))
	// var userID = 3

	//计算扣费总价格
	amount, err := internal.CalculatePrice(db, createInstanceRequest.InstanceType, createInstanceRequest.LeaseTimeSecond)
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}

	//开始订购
	orderRequest := &services.OrderRequest{UserID: uint64(userID), Amount: amount, LeaseTimeSecond: int64(createInstanceRequest.LeaseTimeSecond)}
	// 开始订购流程
	if err := orderProcess.PerformOrder(orderRequest); err != nil {
		err := fmt.Errorf("订购流程失败: %v", err.Error())
		log.Error(err)
		appG.ResponseError(-1, err.Error())
		return
	}
	log.Info(work)
	log.Debugf("订购流程成功")
	response := work.CreateInstanceResponse
	// 将响应转换为所需的格式
	responseData, err := parseResponseData(response.GetHttpContentString())
	if err != nil {
		appG.ResponseError(-1, err.Error())
		return
	}
	appG.ResponseSuccess(gin.H{"response": responseData})
}
